package com.hontech.pastacooking.activity.fragment.sub

import android.view.View
import android.widget.Button
import com.hontech.pastacooking.R
import com.hontech.pastacooking.activity.window.showProg
import com.hontech.pastacooking.app.onClick
import com.hontech.pastacooking.conn.MainProto
import com.hontech.pastacooking.conn.requestMain
import com.hontech.pastacooking.serial.UInt8
import com.hontech.pastacooking.utils.S


class CargoFetchDelegate(view: View) {

    private val btnAdj = view.findViewById<Button>(R.id.id_btn_fetch_adj)
    private val btnLeft = view.findViewById<Button>(R.id.id_btn_fetch_left)
    private val btnCenter = view.findViewById<Button>(R.id.id_btn_fetch_center)
    private val btnRight = view.findViewById<Button>(R.id.id_btn_fetch_right)
    private val btnAutoAdj = view.findViewById<Button>(R.id.id_btn_fetch_auto_adj)

    companion object {
        const val Timeout = 60 * 1000L
        val Msg = S.t17
        const val Req = MainProto.TestCargoFetch
    }

    private suspend fun exec(type: Int) {
        requestMain(Timeout, Req, arrayOf(UInt8(type)), Msg)
    }

    private suspend fun onAutoAdj() {
        val w = showProg(btnAdj, "自动校准")
        try {
            exec(4)
            w.success("自动校准成功")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onAdj() {
        val w = showProg(btnAdj, S.t18)
        try {
            exec(0)
            w.success(S.t19)
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onLeft() {
        val w = showProg(btnAdj, S.t20)
        try {
            exec(1)
            w.success(S.t21)
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onCenter() {
        val w = showProg(btnAdj, S.t22)
        try {
            exec(2)
            w.success(S.t23)
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onRight() {
        val w = showProg(btnAdj, S.t24)
        try {
            exec(3)
            w.success(S.t25)
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }


    init {
        btnAdj.onClick(::onAdj)
        btnLeft.onClick(::onLeft)
        btnCenter.onClick(::onCenter)
        btnRight.onClick(::onRight)
        btnAutoAdj.onClick(::onAutoAdj)
    }
}